package com.ctlele.team.space.activity.impl;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import com.ctlele.team.space.MyApplication;
import com.ctlele.team.space.R;
import com.ctlele.team.space.widget.view.VodPlayerUI;
import com.danikula.videocache.HttpProxyCacheServer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import java.util.Timer;
import java.util.TimerTask;

public class IjkPLayerActivity extends AppCompatActivity {

    private static final String TAG = "IjkPLayerActivity";

    public static final String URL_KEY = "url";

    public static final String CONVERT_KEY = "convert";

    public static final String VIDEO_TITLE_KEY = "video_title";

    private RelativeLayout mPlayerViewContainer;

    private SurfaceView mVideoView;

    private IjkMediaPlayer mPlayer;

    private VodPlayerUI mVodPlayerUI;

    private SeekBar mVideoSeekBar;

    private TextView mCurrTime;

    private TextView mTotalTime;

    private int mVideoViewWidth, mVideoViewHeight;

    private boolean isInit = false;

    TimerTask updateSeekBarTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(() -> {
                if (Math.abs(mPlayer.getDuration() - mPlayer.getCurrentPosition()) < 500) {
                    return;
                }
                mVideoSeekBar.setProgress(calPercent(mPlayer.getCurrentPosition(), mPlayer.getDuration()));
                mCurrTime.setText(formatMilliseconds(mPlayer.getCurrentPosition()));
            });
        }
    };
    Timer executor = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ijk_player);

        String url = getIntent().getStringExtra(URL_KEY);
        String convert = getIntent().getStringExtra(CONVERT_KEY);
        String videoTitle = getIntent().getStringExtra(VIDEO_TITLE_KEY);

        if (TextUtils.isEmpty(url) || !url.startsWith("http")) onBackPressed();

        Log.i(TAG, String.format("Video Url: %s", url));
        HttpProxyCacheServer proxy = MyApplication.getProxy(this);
        url = proxy.getProxyUrl(url);
        Log.i(TAG, String.format("Proxy Url: %s", url));

        // init view
        mPlayer = new IjkMediaPlayer();
        mVideoView = findViewById(R.id.video_view);
        mVodPlayerUI = findViewById(R.id.player_ui);
        mPlayerViewContainer = findViewById(R.id.player_container);
        mVideoSeekBar = mVodPlayerUI.getVideoSeekBar();
        mCurrTime = mVodPlayerUI.getCurrTime();
        mTotalTime = mVodPlayerUI.getTotalTime();

        // VideoView
        mVideoView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                mPlayer.setDisplay(holder);
                mVideoViewWidth = mVideoView.getWidth();
                mVideoViewHeight = mVideoView.getHeight();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
                Log.d(TAG, "surfaceChanged");
            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                Log.d(TAG, "surfaceDestroyed");
            }
        });

        // player
        try {
            mPlayer.setDataSource(url);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            onBackPressed();
        }
        mPlayer.setOnPreparedListener(iMediaPlayer -> {
            mVodPlayerUI.setTotalMs((int) mPlayer.getDuration());
            mTotalTime.setText(formatMilliseconds(mPlayer.getDuration()));
            executor.schedule(updateSeekBarTask, 0, 10);
        });
        // 取消自动播放
        mPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);
        // 设置图像显示模式为 fitCenter
        mPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "scale", "fitCenter");
        mPlayer.prepareAsync();
        mPlayer.setOnVideoSizeChangedListener((iMediaPlayer, i, i1, i2, i3) -> {
            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                fitCenterVideo(mPlayer.getVideoWidth(), mPlayer.getVideoHeight(), mVideoViewWidth, mVideoViewHeight);
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                fitCenterVideo(mPlayer.getVideoWidth(), mPlayer.getVideoHeight(), mVideoViewHeight, mVideoViewWidth);
            }
        });
        mPlayer.setOnCompletionListener(iMediaPlayer -> {
            if (Math.abs(mPlayer.getCurrentPosition() - mPlayer.getDuration()) < 1000) {
                mVodPlayerUI.end();
            }
        });

        // ui
        mVodPlayerUI.setController(new VodPlayerUI.IVodPlayController() {
            @Override
            public void play() {
                isInit = true;
                mPlayer.start();
            }

            @Override
            public void pause() {
                mPlayer.pause();
            }

            @Override
            public void stop() {
                mPlayer.stop();
            }

            @Override
            public void resume() {
                isInit = true;
                mPlayer.start();
            }

            @Override
            public void seek(long time) {
                mPlayer.seekTo(time);
            }

            @Override
            public void playWithTime(long time) {
                isInit = true;
                mPlayer.seekTo(time);
                mPlayer.start();
            }

            @Override
            public void playWithTime(float time) {
            }

            @Override
            public void fullScreen() {
                toFullScreen();
            }

            @Override
            public void unFullScreen() {
                toUnFullScreen();
            }
        });
        // 加载封面图
        if (!TextUtils.isEmpty(convert)) mVodPlayerUI.setConvertPicture(convert);
        mVodPlayerUI.setVideoTitle(videoTitle);
        mVodPlayerUI.setOnBackPressed((view) -> onBackPressed());

        // ui visible
        mPlayerViewContainer.setOnClickListener(item -> {
            if (!isInit) return;
            if (mVodPlayerUI.getVisibility() == View.INVISIBLE) {
                mVodPlayerUI.setVisibility(View.VISIBLE);
            } else {
                mVodPlayerUI.setVisibility(View.INVISIBLE);
            }
        });
    }

    void toFullScreen() {
        // TODO: 全屏状态下向下滑动，状态栏会出现且无法二次消失

        // 隐藏状态栏和虚拟按键
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
        decorView.setSystemUiVisibility(uiOptions);
        // 设置横屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        // 隐藏ActionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        fitCenterVideo(mPlayer.getVideoWidth(), mPlayer.getVideoHeight(), mVideoViewHeight, mVideoViewWidth);
    }

    void toUnFullScreen() {
        // 还原为竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        // 显示状态栏和导航栏
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
        decorView.setSystemUiVisibility(uiOptions);
        // 显示ActionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.show();
        }
        fitCenterVideo(mPlayer.getVideoWidth(), mPlayer.getVideoHeight(), mVideoViewWidth, mVideoViewHeight);
    }

    public void fitCenterVideo(int videoWidth, int videoHeight, int surfaceWidth, int surfaceHeight) {
        Log.i(TAG, String.format("videoWidth: %s videoHeight: %s", videoWidth, videoHeight));
        Log.i(TAG, String.format("surfaceWidth: %s surfaceHeight: %s", surfaceWidth, surfaceHeight));

        // 图像原始的宽高比
        double ratio = (double) videoWidth / videoHeight;

        int scaleWidth, scaleHeight;
        // 根据窗口的宽高去处理 短边要撑满 长边要缩放
        if (surfaceWidth > surfaceHeight) {
            // 宽大于高 横屏
            scaleHeight = surfaceHeight;
            scaleWidth = (int) (scaleHeight * ratio);
        } else {
            // 宽小于高 竖屏
            scaleWidth = surfaceWidth;
            scaleHeight = (int) (scaleWidth / ratio);
        }

        Log.i(TAG, String.format("scaleWidth: %s scaleHeight: %s", scaleWidth, scaleHeight));
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(scaleWidth, scaleHeight);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, mPlayerViewContainer.getId());
        mVideoView.setLayoutParams(params);
    }

    public static int calPercent(long subtotal, long total) {
        if (total == 0) {
            return 0;
        }
        double percentage = (double) subtotal / total * 100;
        return (int) Math.round(percentage);
    }

    public static String formatMilliseconds(long milliseconds) {
        long seconds = (milliseconds / 1000) % 60;
        long minutes = (milliseconds / (1000 * 60)) % 60;
        long hours = (milliseconds / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    @Override
    public void onBackPressed() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
        }
        updateSeekBarTask.cancel();
        executor.cancel();
        super.onBackPressed();
    }
}